package 左叶子之和;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 给定二叉树的根节点 root ，返回所有左叶子之和。
 * @date 2022/11/3 12:00
 */
public class Demo404 {
    public int sumOfLeftLeaves(TreeNode root) {
        int sum=0;
        if(root==null){
            return 0;
        }
        //左节点做，左叶子节点数之和
        int sum1 = addSum(root.left, sum, 1);
        //右节点做，左叶子节点数之和
        int sum2 = addSum(root.right, sum, 2);
        return sum1+sum2;
    }
    //递归三部曲
    private int addSum(TreeNode root, int sum, int index) {
         //终止条件
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            if(index==1){
               sum=sum+root.val;
            }
            return sum;
        }
       return addSum(root.left,sum,1)+addSum(root.right,sum,2);

    }

    //Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
